<?php
/**
 * Created by PhpStorm.
 * User: papa
 * Date: 18/5/11
 * Time: 07:56
 */

namespace app\api\lib\exception;


use think\exception\Handle;
use Exception;
use think\Request;

/*
 * 重写Handle的render方法，实现自定义异常消息
 * 详细参考tp5开发手册处理异常文档
 */
class ExceptionHandler extends Handle
{
    private $code;
    private $msg;
    private $status;
    private $data = array();

    public function render(Exception $e)
    {
        if ($e instanceof BaseException)
        {
            //如果是自定义异常
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->status = $e->status;
            $this->data = $e->data;
        }
        else{
            // 如果是服务器自身异常，并且开启了debug调试模式
            if(config('app_debug')){
                return parent::render($e);
            }
            //如果没有开启debug模式，将状态码设置位500
            $this->code = 500;
            $this->msg = 'sorry，we are busy';
            $this->status = 'false';
        }

        $request = Request::instance();
        $result = [
            'msg'  => $this->msg,
            'status' => $this->status,
            'data'  => $this->data,
            'request_url' => $request->domain().$request->url() //获取当前url
        ];
        return json($result, $this->code);
    }
}